package com.example.zjx8969.myapplication

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.SurfaceTexture
import android.media.MediaMetadataRetriever
import android.media.MediaPlayer
import android.util.AttributeSet
import android.util.Log
import android.view.Surface
import android.view.TextureView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.coroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream

/*

class PreviewSurfaceView @JvmOverloads constructor(context: Context, attr: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0) : TextureView(context, attr, defStyleAttr, defStyleRes),
        MediaPlayer.OnPreparedListener, TextureView.SurfaceTextureListener {
    private val videoWidth = 496
    private val videoHeight = 1080
    private var surfaceVar: Surface? = null
    private val paint = Paint()
    private var startPreview = false
    private var loadThumbnailTask: Job? = null
    private var videoPath: String? = null
    private var mediaPlayer: MediaPlayer? = null
    private lateinit var mediaPool: MediaPlayerPool
    private var isPrepared = false

    init {
        surfaceTextureListener = this
    }

    fun setMediaPlayerPool(mediaPlayerPool: MediaPlayerPool) {
        mediaPool = mediaPlayerPool
    }

    fun setAssertVideoAndPreview(lifecycle: Lifecycle, path: String) {
        videoPath = path
        startPreview = true
        loadThumbnailTask?.cancel()
        loadThumbnailTask = lifecycle.coroutineScope.launch(Dispatchers.Default) {
            val mediaMetadataRetriever = MediaMetadataRetriever()
            context.assets.openFd(path).use {
                mediaMetadataRetriever.setDataSource(it.fileDescriptor, it.startOffset, it.length)
            }
            val bitmap = mediaMetadataRetriever.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
//            val desiredMatrix = getDesiredMatrix(bitmap.width, bitmap.height)
            val destMap = getScaleBitmap(bitmap)
            Log.e("tag", "${destMap.width}, ${destMap.height},view:{$width, $height} viewRatio= ${1f * width / height}, mapRatio=${1f * destMap.width / destMap.height}")
            bitmap.recycle()
            while (startPreview) {
                val canvas = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) surfaceVar?.lockHardwareCanvas()
                else surfaceVar?.lockCanvas(null)
                if (canvas != null) {
                    canvas.drawBitmap(destMap, 0f, 0f, paint)
                    surfaceVar?.unlockCanvasAndPost(canvas)
                }
                delay(100)
            }

        }
    }

    fun saveImage(bitmap: Bitmap, name: String) {
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(File(context.getExternalFilesDir(null), "$name.jpg")))
    }

    fun startPlayVideo() {
        if (videoPath.isNullOrEmpty()) return
        startPreview = false
        if (isPrepared) mediaPlayer?.start()
    }

    private fun setupPlayer() {
        if (videoPath == null) return
        isPrepared = false
        mediaPlayer = mediaPool.getMediaPlayer().apply {
            isLooping = true
            setOnPreparedListener(this@PreviewSurfaceView)
            mediaPool.markInUse(this)
        }
        surfaceVar?.let { mediaPlayer?.setSurface(surfaceVar) }
*/
/*        mediaPlayer?.setOnVideoSizeChangedListener { _, width, height ->
            if (width == 0 || height == 0) return@setOnVideoSizeChangedListener
            val matrix = getDesiredMatrix(width, height)
            setTransform(matrix)
        }*//*

        context.assets.openFd(videoPath!!).use {
            mediaPlayer?.setDataSource(it.fileDescriptor, it.startOffset, it.length)
        }
        mediaPlayer?.prepareAsync()
    }

    private fun getScaleBitmap(bitmap: Bitmap): Bitmap {
        val scaleX = 1f * width / bitmap.width
        val scaleY = 1f * height / bitmap.height
        val scale = Matrix()
        scale.postScale(scaleX, scaleY)
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, scale, true)

    }


    fun startPlayWithThumb(lifecycle: Lifecycle, assertPath: String) {
        setAssertVideoAndPreview(lifecycle, assertPath)
        startPlayVideo()
    }

    fun stopPreview() {
        startPreview = false
        loadThumbnailTask?.cancel()
        if (mediaPlayer?.isPlaying == true) mediaPlayer?.pause()
    }

    override fun onPrepared(mp: MediaPlayer?) {
        isPrepared = true
        loadThumbnailTask?.cancel()
        surfaceVar?.let { mp?.setSurface(surfaceVar) }
        mp?.start()
    }

*/
/*    override fun surfaceCreated(holder: SurfaceHolder?) {
        setupPlayer()
    }*//*


//    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {}

*/
/*    override fun surfaceDestroyed(holder: SurfaceHolder?) {
        isPrepared = false
        stopPreview()
        mediaPlayer?.let {
            mediaPool.recycle(it)
        }
    }*//*


    override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) {
        surfaceVar = Surface(surface)
        setupPlayer()
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture?, width: Int, height: Int) {}

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?): Boolean {
        surfaceVar = null
        isPrepared = false
        stopPreview()
        mediaPlayer?.let {
            mediaPool.recycle(it)
        }
        return true
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) {}

    fun logInfo(content: String) {
        Log.e("surface", "$videoPath, $content")
    }

}*/
